package com.cb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cb.common.BaseContext;
import com.cb.entity.AddressBook;
import com.cb.mapper.AddressBookMapper;
import com.cb.service.AddressBookService;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements AddressBookService {
    @Override
    public List<AddressBook> getList(Long currentId) {
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(currentId!=null,AddressBook::getUserId,currentId);
        queryWrapper.orderByDesc(AddressBook::getUpdateTime);
        List<AddressBook> list = list(queryWrapper);
        return list;
    }

    @Override
    public AddressBook setDefault(AddressBook addressBook) {
        //update address_book set is_default = 0 where user_id = ?
        LambdaUpdateWrapper<AddressBook> queryWrapper = new LambdaUpdateWrapper<>();
        queryWrapper.eq(AddressBook::getUserId,addressBook.getUserId());
        queryWrapper.set(AddressBook::getIsDefault,0);
        update(queryWrapper);

        //update address_book set is_default = 1 where id = ?
        addressBook.setIsDefault(1);
        updateById(addressBook);
        return addressBook;
    }

    @Override
    public void updateAddress(AddressBook addressBook) {
        updateById(addressBook);
    }

    @Override
    public AddressBook getDefault() {
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        Long currentId = BaseContext.getCurrentId();
        queryWrapper.eq(AddressBook::getUserId,currentId);
        queryWrapper.eq(AddressBook::getIsDefault,1);
        //select * from address_book where user_id = ? and is_default = 1
        AddressBook addressBook = getOne(queryWrapper);
        return addressBook;
    }
}
